/**
 Copyright (c) 2007, Fanhuagang

 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this list
 of conditions and the following disclaimer.
 Redistributions in binary form must reproduce the above copyright notice, this
 list of conditions and the following disclaimer in the documentation and/or other
 materials provided with the distribution.
 Neither the name of the Fanhuagang nor the names of its contributors may be used
 to endorse or promote products derived from this software without specific prior
 written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */
package van.mvn;

import com.intellij.ide.wizard.CommitStepException;
import com.intellij.ide.wizard.StepAdapter;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.IconLoader;
import org.apache.maven.model.Dependency;
import org.jetbrains.annotations.Nullable;
import van.index.Indexer;
import van.index.MavenRepositoryIndexManager;
import van.maven.MavenRunner;
import van.maven.MyDownloadMonitor;
import van.maven.MyEventMonitor;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Set;

/**
 * Step 1: input archetype crietia and generate project.
 * <p/>
 * User can input archetype field all by hand or use a search dialog to choose one.
 * <p/>
 * When user click NEXT, maven will do create maven project process in background untill done. then show the
 * result panel.
 * <p/>
 * If user click FINISH. maven will also do create maven project process in background but do not show
 * the result panel.
 * <p/>
 * User: Fanhuagang
 * Date: 2007-10-5 Time: 20:56:30
 */
public class MvnProjectWizardStep extends StepAdapter {
    private Project myProject;
    private MvnProjectContext context;
    private JTextField archetypeArtifactId;
    private JTextField archetypeGroupId;
    private JTextField archetypeVersion;
    private JTextField remoteRepositories;
    private JTextField groupId;
    private JTextField artifactId;
    private TextFieldWithBrowseButton basedir;

    private JPanel centerPanel;
    private JButton search;

    public JTextField getArchetypeArtifactId() {
        return archetypeArtifactId;
    }

    public JTextField getArchetypeGroupId() {
        return archetypeGroupId;
    }

    public JTextField getArchetypeVersion() {
        return archetypeVersion;
    }

    public JTextField getRemoteRepositories() {
        return remoteRepositories;
    }

    public JTextField getGroupId() {
        return groupId;
    }

    public JTextField getArtifactId() {
        return artifactId;
    }

    public TextFieldWithBrowseButton getBasedir() {
        return basedir;
    }

    public MvnProjectWizardStep(Project project, MvnProjectContext context) {
        myProject = project;
        this.context = context;
    }

    public void _init() {
        super._init();
        this.archetypeArtifactId.setText(context.getArchetypeArtifactId());
        this.archetypeGroupId.setText(context.getArchetypeGroupId());
        this.archetypeVersion.setText(context.getArchetypeVersion());
        this.remoteRepositories.setText(context.getRemoteRepositories());
        this.basedir.setText(context.getBasedir());
    }

    public void _commit(boolean finishChosen) throws CommitStepException {
        super._commit(finishChosen);
        context.setArchetypeArtifactId(archetypeArtifactId.getText());
        context.setArchetypeGroupId(archetypeGroupId.getText());
        context.setArchetypeVersion(archetypeVersion.getText());
        context.setRemoteRepositories(remoteRepositories.getText());
        context.setBasedir(basedir.getText());

        /*ArrayList<String> list = new ArrayList<String>();
        list.add("archetype:create");
        list.add("-DgroupId=" + groupId.getText());
        list.add("-DartifactId=" + artifactId.getText());
        list.add("-DarchetypeArtifactId=" + archetypeArtifactId.getText());
        list.add("-DarchetypeGroupId=" + archetypeGroupId.getText());
        list.add("-DarchetypeVersion=" + archetypeVersion.getText());
        list.add("-Duser.dir=" + basedir.getText());
        if (!"".equals(remoteRepositories.getText().trim())) {
            list.add("-DremoteRepositories=" + remoteRepositories.getText());
        }

        final String[] args = list.toArray(new String[list.size()]);*/

        // use MavenCli directly
        /*final ProgressManager progressManager = ProgressManager.getInstance();
        boolean result = progressManager.runProcessWithProgressSynchronously(new Runnable() {
            public void run() {
                ClassWorld classWorld = new ClassWorld("plexus.core", MvnProjectWizardStep.class.getClassLoader());
                MavenCli.main(args, classWorld);
            }
        }, MvnBundle.getString("create.mavan.project"), true, myProject);*/

        // use MavenRunner with progress indicator instead
        /*final ProgressManager progressManager = ProgressManager.getInstance();
        progressManager.run(new Task.Modal(myProject, MvnBundle.getString("create.mavan.project"), false) {
            public void run(ProgressIndicator indicator) {
                ClassWorld classWorld = new ClassWorld("plexus.core", MavenRunner.class.getClassLoader());

                MavenRunner mavenRunner = new MavenRunner();
                mavenRunner.setProgressIndicator(indicator);
                mavenRunner.setIndexManager(ServiceManager.getService(MvnProjectComponent.class).getMavenRepositoryIndexManager());
                indicator.setText("Generate project...");
                mavenRunner.doMain(args, classWorld);
            }
        });*/


        // new MavenRunner depends on IDEA maven plugin
        final ProgressManager progressManager = ProgressManager.getInstance();
        progressManager.run(new Task.Modal(myProject, MvnBundle.getString("create.mavan.project"), false) {
            public void run(ProgressIndicator indicator) {

                MavenRepositoryIndexManager mavenRepositoryIndexManager = ServiceManager.getService(MvnProjectComponent.class).getMavenRepositoryIndexManager();
                indicator.setText("Generate project...");
                new MavenRunner(myProject)
                        .setTransferListener(new MyDownloadMonitor(indicator, mavenRepositoryIndexManager))
                        .setEventMonitor(new MyEventMonitor(indicator))
                        .execute(
                        basedir.getText(),
                        archetypeArtifactId.getText(),
                        archetypeGroupId.getText(),
                        archetypeVersion.getText(),
                        remoteRepositories.getText(),
                        groupId.getText(),
                        artifactId.getText(),
                        "1.0"
                );

            }
        });
    }

    public JComponent getComponent() {
        return centerPanel;
    }

    @Nullable
    public Icon getIcon() {
        return IconLoader.getIcon("/images/newmavenproject.png");
    }


    private void createUIComponents() {
        basedir = new TextFieldWithBrowseButton();
        FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
        basedir.addBrowseFolderListener(MvnBundle.getString("choose.project.root"), MvnBundle.getString("choose.project.root.description"), myProject, descriptor);

        search = new JButton();
        search.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MavenRepositorySearchDialog dialog = new MavenRepositorySearchDialog(myProject, false, "archetype");
                dialog.setTitle("Search Archetype");
                dialog.show();
                if (!dialog.isOK()) return;

                Object result = dialog.getData();
                if (result instanceof Indexer.FileInfo) {
                    Dependency dependency = ((Indexer.FileInfo) result).getDependency();
                    archetypeArtifactId.setText(dependency.getArtifactId());
                    archetypeGroupId.setText(dependency.getGroupId());
                    archetypeVersion.setText(dependency.getVersion());
                } else if (result instanceof Indexer.ArtifactInfo) {
                    // If we have an ArtifactInfo, we add the first FileInfo it contains
                    // which corresponds to the latest version of the artifact.
                    Set files = ((Indexer.ArtifactInfo) result).files;
                    if ((files != null) && (files.size() > 0)) {
                        Object file = files.iterator().next();
                        if (file instanceof Indexer.FileInfo) {
                            Dependency dependency = ((Indexer.FileInfo) file).getDependency();
                            archetypeArtifactId.setText(dependency.getArtifactId());
                            archetypeGroupId.setText(dependency.getGroupId());
                            archetypeVersion.setText(dependency.getVersion());
                        }
                    }
                }
            }
        });
    }


}
